<template>
  <div class="login g-flex" v-loading="pageLoading">
    <template v-if="showLoginPage">
      <div class="left-wrap">
        <img class="logo" :src="platformImg" />
        <img class="bg-theme" :src="platformBgImg" />
      </div>
      <div class="right-wrap">
        <p class="g-font-24n1b500 g-mb48">账号密码登录</p>
        <el-form
          ref="formRef"
          :model="formState"
          :rules="rules"
          label-width="0"
          size="large"
          hide-required-asterisk
          @submit.prevent
        >
          <el-form-item class="g-mb16" prop="username">
            <el-input
              class="login-input"
              v-model.trim="formState.username"
              placeholder="请输入邮箱/手机号/工号"
              autocomplete="off"
              :maxlength="30"
              clearable
              :disabled="loading"
              @keyup.enter="loginConfirmInput"
            ></el-input>
          </el-form-item>
          <el-form-item class="g-mb20" prop="password">
            <el-input
              class="login-input"
              type="password"
              v-model.trim="formState.password"
              placeholder="请输入密码"
              autocomplete="off"
              :maxlength="16"
              show-password
              clearable
              :disabled="loading"
              @keyup.enter="loginConfirmInput"
            ></el-input>
          </el-form-item>
          <el-form-item class="g-mb11">
            <el-button class="login-button" type="primary" @click="handleLogin" :loading="loading"
              >立即登录</el-button
            >
          </el-form-item>
        </el-form>
        <div class="g-mb23">
          <span class="g-font-14n2">忘记密码？</span>
          <span class="login-reset" @click="resetVisible = true">找回密码</span>
        </div>
        <p class="g-font-14n2 g-mb16"></p>
        <el-divider border-style="dashed" class="other-login">其他登录方式</el-divider>

        <div class="g-flex">
          <template v-for="item in loginPlatform" :key="item">
            <div class="login-img" @click="handleRouterToDingtalkLogin" v-if="item == 'DINGTALK'">
              <img src="@/assets/images/login_dingding.png" />
            </div>
            <div class="login-img" @click="handleRouterToOALogin" v-if="item == 'OA'">OA</div>
            <div class="login-img" @click="handleRouterToFeishuLogin" v-if="item == 'FEISHU'">
              <img src="@/assets/images/login_feishu.png" />
            </div>
          </template>
        </div>
      </div>
      <CResetDialog v-model:visible="resetVisible"></CResetDialog>
    </template>
  </div>
</template>
<script lang="ts" setup name="Login">
import { ref, UnwrapRef, reactive, computed } from 'vue'
import { encrypt } from '@/utils/crypto'
import { useRoute, useRouter } from 'vue-router'
import { store } from '@/store'
import { UserActionTypes } from '@/store/modules/user/action-types'
import { useLogin } from './useLogin'
import CResetDialog from '@/businessComponents/CResetDialog/index.vue'
import { PATH_CONFIG } from '@/commonModule/config'

interface FormState {
  username: string
  password: string
}
const router = useRouter()
const route = useRoute()
const loading = ref(false)
const { checkLoginPlatform, pageLoading, showLoginPage } = useLogin()
checkLoginPlatform()
const isDev = import.meta.env.NODE_ENV == 'development'
const formState: UnwrapRef<FormState> = reactive({
  username: isDev ? import.meta.env.VUE_APP_LOGIN_USERNAME || '' : '',
  password: isDev ? import.meta.env.VUE_APP_LOGIN_PASSWORD || '' : ''
})
const rules = reactive({
  username: [
    {
      required: true,
      message: '账号不能为空',
      trigger: ['submit', 'change']
    }
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: ['submit', 'change']
    }
  ]
})
const formRef = ref()
const platform = computed(() => {
  return window.PLATFORM || 'CMP'
})

const platformImg = computed(() => {
  return new URL(`@/assets/images/logo_${platform}.png`, import.meta.url).href
})
const platformBgImg = computed(() => {
  return new URL(`@/assets/images/login_bg_${platform}.png`, import.meta.url).href
})
const loginConfirm = async () => {
  // TODO去掉验证码
  const params = {
    username: formState.username,
    password: encrypt(formState.password)
  }
  loading.value = true
  try {
    await store.dispatch(UserActionTypes.ACTION_LOGIN, { userInfo: params, loginType: 'PWD' })
    const { redirect } = route.query
    let path = PATH_CONFIG.HOME_PAGE
    if (redirect) {
      // 如果是外链，则直接加载
      if (redirect.indexOf('http') > -1) {
        ;(window as any).location.href = redirect
        return
      }
      if (!['/404', '401'].includes(redirect as string)) {
        path = redirect as string
      }
    }
    router.push(path)
  } catch (error: any) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

const loginConfirmInput = () => {
  if (formState.username && formState.password) {
    handleLogin()
  }
}

const handleLogin = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loginConfirm()
    }
  })
}

const resetVisible = ref(false)
const loginPlatform = computed(() => {
  return window.LOGIN_PLATFORM ?? []
})
// 跳转到飞书账号登录页面
function handleRouterToFeishuLogin() {
  const redirectUri = encodeURIComponent(`${window.location.origin}/login`)
  window.location.href = `https://open.feishu.cn/open-apis/authen/v1/index?redirect_uri=${redirectUri}&app_id=${window.FEISHU_ID}&state=FEISHU`
}
// 跳转到oa登录页面
function handleRouterToOALogin() {
  const redirectUri = encodeURIComponent(`${window.location.origin}/login?platform=OA`)
  window.location.href = `${window.OA_LOGIN_URL}${redirectUri}`
}
// 跳转到钉钉账号登录页面
function handleRouterToDingtalkLogin() {
  const redirectUri = encodeURIComponent(`${window.location.origin}/login`)
  window.location.href = `https://login.dingtalk.com/oauth2/challenge.htm?client_id=${window.DINGTALK_ID}&redirect_uri=${redirectUri}&scope=openid&response_type=code`
}
</script>
<style lang="scss" scoped>
.login {
  position: relative;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  background: #fff;
  .left-wrap {
    position: relative;
    flex: 1;
    background: linear-gradient(180deg, #01775a 0%, #08b88d 100%);
    display: flex;
    justify-content: center;
    align-items: center;
    .logo {
      position: absolute;
      left: 10px;
      top: 10px;
      height: 50px;
    }
    .bg-theme {
      width: 700px;
      height: 700px;
    }
  }
  .right-wrap {
    width: 576px;
    background:
      url('~@/assets/images/bg_login.png') left bottom no-repeat,
      rgba(255, 255, 255);
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 183px;

    .login-input {
      width: 378px;
      height: 48px;
      :deep(.el-input__wrapper) {
        padding-left: 16px;
        height: 48px;
        line-height: 48px;
      }
    }
    .login-button {
      width: 378px;
      height: 40px;
      font-size: 14px;
    }
    .login-reset {
      height: 22px;
      font-size: 14px;
      color: #308bf2;
      line-height: 22px;
      cursor: pointer;
    }
    .other-login {
      width: 378px;
      border-top: 1px dashed #e1e6eb; /*设置边框为5px宽的黑色虚线*/
    }
    .login-img {
      margin-top: 2px;
      width: 48px;
      height: 48px;
      background: #ffffff;
      border-radius: 6px;
      border: 1px solid #ebeff2;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .login-img + .login-img {
      margin-left: 16px;
    }
  }
}
</style>
